package com.ruoyi.system.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.json.Json;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Math.min;

public class ISDataScoreUtil {
    /**
     *  指标id : name
     */
    public  Map<Integer,String> indicatorMap = new HashMap<>();
    public void setIndicatorMap(){
        /** 中国主导 */
        indicatorMap.put(3,"A1");
        indicatorMap.put(4,"A2");
        indicatorMap.put(5,"A3");
        indicatorMap.put(6,"B1");
        indicatorMap.put(7,"B2");
        indicatorMap.put(8,"B3");

        /** 中国参与 */
        indicatorMap.put(40,"A11");
        indicatorMap.put(41,"A12");
        indicatorMap.put(42,"A13");

        indicatorMap.put(43,"A23");
        indicatorMap.put(44,"A22");
        indicatorMap.put(45,"A21");

        indicatorMap.put(46,"A31");
        indicatorMap.put(47,"A32");
        indicatorMap.put(48,"A33");

        indicatorMap.put(51,"A42");
        indicatorMap.put(52,"A43");
        indicatorMap.put(53,"A41");

        indicatorMap.put(54,"B11");
        indicatorMap.put(55,"B12");
        indicatorMap.put(57,"B13");

        indicatorMap.put(70,"B21");
        indicatorMap.put(71,"B22");
        indicatorMap.put(58,"B23");

        indicatorMap.put(69,"B31");
        indicatorMap.put(60,"B32");
        indicatorMap.put(61,"B33");

        indicatorMap.put(68,"B41");
        indicatorMap.put(63,"B42");
        indicatorMap.put(62,"B43");

        indicatorMap.put(67,"B51");
        indicatorMap.put(65,"B52");
        indicatorMap.put(66,"B53");

        indicatorMap.put(30,"C11");
    }
    public Map<Integer, String> getIndicatorMap() {
        return indicatorMap;
    }
    /**
     * usage : paramsType
     */
    public Map<String,String> paramsTypeMap = new HashMap<>();
    public void setParamsTypeMap(){
        /** 中国主导 */
        paramsTypeMap.put("投票通过次数","x");
        paramsTypeMap.put("会议组织次数","x");
        paramsTypeMap.put("邮件总数","y");
        paramsTypeMap.put("邮件回复数","x");
        paramsTypeMap.put("最初提案","file1_path");
        paramsTypeMap.put("最终文本","file2_path");
        paramsTypeMap.put("专家打分","x");

        /** 中国参与 */
        paramsTypeMap.put("投票记录","vote_record_path");
        paramsTypeMap.put("会议记录","meeting_record_path");
        paramsTypeMap.put("中国专家数量","x");
        paramsTypeMap.put("邮件数量","x");
    }
    public Map<String, String> getParamsTypeMap() {
        return paramsTypeMap;
    }

    /**
     * 指标id:usage
     */


    public ISDataScoreUtil(){
        setIndicatorMap();
        setParamsTypeMap();
    }



    public String calScore(Integer type, JSONObject paramsOB){
        RestTemplate restTemplate = new RestTemplate();

        String url = "";
        if (type == 0){/** 中国主导 */
            url = "http://127.0.0.1:5000/calCNLead";
        }else if (type == 1) {/** 中国参与 */
            url = "http://127.0.0.1:5001/calCNJoin";
        }else{
            return "Error: Invalid type";
        }

        String params = paramsOB.toJSONString();
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 将请求头和请求体封装成HttpEntity
        HttpEntity<String> entity = new HttpEntity<>(params, headers);

        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            JSONObject resOB = JSON.parseObject(response.getBody());
            return resOB.getString("calRes");
        } catch (HttpClientErrorException e) {
            System.err.println("Request failed: " + e.getMessage());
            return "Request failed";
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            return "Error occurred";
        }
    }




    /**
     * 中国主导 ————————————————
     * target : "B1"
     * params : {"x":4,"y":6,"file1_path":"path1","file2_path":"path2"}
     */
    public  String cal_CN_Lead(String target , String params){
        try {
            // Python 编辑器
            String pythonInterpreter = "E:\\Code\\Python\\VideoAnalysis\\.venv\\Scripts\\python.exe";
            // Python 脚本路径
            String scriptPath = "E:\\Code\\Python\\VideoAnalysis\\CN_Lead\\cal_CN_Lead.py";

            // 脚本运行命令
            List<String> command = new ArrayList<>();
            command.add(pythonInterpreter);
            command.add(scriptPath);
            command.add(target);    // sys.argv[1]
            command.add(params);    // sys.argv[1]

            // 执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF-8"));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            process.waitFor();

            // 提取最后一行--即结果
            String outputStr = output.toString().trim();

            String[] lines = outputStr.split("\n");
            String res = lines.length > 0 ? lines[lines.length - 1] : "No output found";

            return res;

        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }


    /**
     * 中国参与 ————————————————
     * target : "A21"
     * params : {"x":4,,"vote_record_path":"path1","meeting_record_path":"path2"}
     */
    public String cal_CN_Join(String target,String params){
        try {
            // Python 编辑器
            String pythonInterpreter = "E:\\Code\\Python\\VideoAnalysis\\.venv\\Scripts\\python.exe";
            // Python 脚本路径
            String scriptPath = "E:\\Code\\Python\\VideoAnalysis\\CN_Join\\cal_CN_Join.py";

            // 脚本运行命令
            List<String> command = new ArrayList<>();
            command.add(pythonInterpreter);
            command.add(scriptPath);
            command.add(target);    // sys.argv[1]
            command.add(params);    // sys.argv[1]

            // 执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF-8"));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            process.waitFor();

            // 提取最后一行--即结果
            String outputStr = output.toString().trim();
            String[] lines = outputStr.split("\n");
            String res = lines.length > 0 ? lines[lines.length - 1] : "No output found";

            return res;

        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }


}
